<template>
  <div>
    <el-button
      icon="el-icon-download"
      type="text"
      @click="download"
    >导出vue文件
    </el-button>
    <CodeTypeDialog
      v-model="isShowExportFileDialog"
      v-if="isShowExportFileDialog"
      @confirm="genVueFile"
    />
    <el-button
      class="copy-btn-main"
      icon="el-icon-document-copy"
      type="text"
      @click="copy"
    >复制代码
    </el-button>
    <input id="copyNode" type="hidden">
    <el-button
      class="delete-btn"
      icon="el-icon-delete"
      type="text"
      @click="$emit('empty')"
    >清空
    </el-button>
  </div>
</template>

<script>
  import { saveAs } from 'file-saver'
  import generateVueScriptString from './utils/js'
  import generateVueTemplate from './utils/html'
  import generateCssStyle from './utils/css'
  import CodeTypeDialog from './CodeTypeDialog'
  import beautifier from 'js-beautify'
  import { beautifierConf } from '@/views/edit/config'
  import ClipboardJS from 'clipboard'

  export default {
    name: 'ExportVueCode',
    components: {
      CodeTypeDialog
    },
    props: {
      drawingList: {
        type: Array,
        default: () => ([])
      },
      formConf: {
        type: Object,
        default: () => ({})
      }
    },
    mounted () {
      const clipboard = new ClipboardJS('#copyNode', {
        text: () => {
          const codeStr = this.generateCode()
          this.$notify({
            title: '成功',
            message: '代码已复制到剪切板，可粘贴。',
            type: 'success'
          })
          return codeStr
        }
      })
      clipboard.on('error', e => {
        this.$message.error('代码复制失败')
      })
    },
    data () {
      return {
        isShowExportFileDialog: false
      }
    },
    methods: {
      genVueFile (data) {
        const codeStr = this.generateCode(data)
        const blob = new Blob([codeStr], { type: 'text/plain;charset=utf-8' })
        saveAs(blob, data.fileName)
      },
      generateCode () {
        const conf = {
          componentsConf: this.drawingList,
          formConf: this.formConf
        }
        const script = generateVueScriptString(conf)
        const html = generateVueTemplate(conf)
        const css = generateCssStyle(conf)
        return beautifier.html(html + script + css, beautifierConf.html)
      },
      download () {
        this.isShowExportFileDialog = true
      },
      copy () {
        document.getElementById('copyNode')
          .click()
      }
    }
  }
</script>

<style scoped>

</style>
